/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.service.impl;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import org.apache.log4j.Logger;
import org.app.dto.google.ResponseDataJson;
import org.app.model.QueueURLs;
import org.app.service.GoogleService;
import org.app.utils.PropertiesHelper;
import org.app.utils.PropertyUtils;
import org.app.utils.Utils;
import org.gui.AutoDownloadMovieGUI;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author LamLe
 */
public class GoogleDisableJS_ServiceImpl extends GoogleAbstract implements GoogleService {

    private static Logger logger = Logger.getLogger(GoogleDisableJS_ServiceImpl.class);
    public static String cookies = "";

    public GoogleDisableJS_ServiceImpl(AutoDownloadMovieGUI main) {
        super(main);
    }

    @Override
    public ResponseDataJson search(String movieName) throws Exception {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public ResponseDataJson search(String movieName, int page, ResponseDataJson json) throws Exception {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public ResponseDataJson search24(String movieName) throws Exception {
        ResponseDataJson results = new ResponseDataJson();
        try {
            // init first time or restore from cookies browser.properties
            initFirstTime();
            movieName = generateUrl(movieName);
            movieName = "&q=" + movieName;
            Connection conn = Jsoup.connect("http://www.google.com.vn/search?hl=vi&source=hp&biw=&bih=&btnG=T%C3%ACm+v%E1%BB%9Bi+Google&gbv=1" + movieName)
                    .header("Cookie", cookies)
                    .header("Referer", "http://www.google.com.vn/");
            Utils.initRequestHeader(conn);
            htmlParse(conn.get());
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace(System.out);
            throw e;
        }
        return results;
    }

    private void initFirstTime() throws Exception {
        // first time
        cookies = PropertyUtils.getProperty(PropertiesHelper.GOOGLE_COOKIES);
        if (cookies.equals("")) {
            URL url = new URL("http://www.google.com.vn/");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // init heaeder
            initRequestHeader(conn, "www.google.com.vn");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
            conn.connect();
            // get cookies , store to browser.properties for next times
            cookies = getResponseHeader(conn, "SET-Cookie");
            // write to google properties
            PropertyUtils.setProperty(PropertiesHelper.GOOGLE_COOKIES, cookies);
            PropertyUtils.saveProperty();
        }
    }

    private ResponseDataJson parseGoogleResult(String html) {
        ResponseDataJson results = new ResponseDataJson();
        try {
            String s = html;
            String str[] = s.split("<h3 class=\"r\">");
            for (String q : str) {
                String str_[] = q.split("</h3>");
                for (String w : str_) {
                    if (w.indexOf("<a href=") == 0) {
                        w = w.replace("<a href=\"/url?q=", "");
                        w = w.substring(0, w.indexOf("&amp;sa="));
                        // link from google
                        logger.info(w);
                        QueueURLs.add(w);
                    }
                }
            }
            String pages[] = s.split("<span class=\"csb\"");
            for (String p : pages) {
                if (p.contains("search?q=") && p.contains("background-position:") && p.contains("class=\"fl\">")) {
                    logger.info(p.substring(p.indexOf("<a href=\"") + 9, p.indexOf("\" class=\"fl\">")));
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return results;
    }

    public static void main(String a[]) {
        new GoogleDisableJS_ServiceImpl(null).htmlParse("");
    }

    private void start() {
        parseGoogleResult("");
    }

    private void htmlParse(String html) {
        try {
            //File in = new File("resources/result.html");
            //Document doc = Jsoup.parse(in, "UTF-8");
            Document doc = Jsoup.parse(html);
            Elements links = doc.select("div#ires li h3.r a");
            for (Element e : links) {
                String url = e.select("a").attr("href");
                url = url.substring(7, url.indexOf("&sa=U"));
                url = URLDecoder.decode(url, "UTF-8");
                logger.info(url);
                QueueURLs.add(url);
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

    private void htmlParse(Document doc) {
        try {
            Elements links = doc.select("div#ires li h3.r a");
            for (Element e : links) {
                String url = e.select("a").attr("href");
                url = url.substring(7, url.indexOf("&sa=U"));
                url = URLDecoder.decode(url, "UTF-8");
                logger.info(url);
                QueueURLs.add(url);
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}
